#include "UserData.h"
#include <mutex>
#include <QCoreApplication>
#include <QDir>
#include "../XXqtDefine.h"

#define kSystem "_system_"
#define kApp "_app_"

UserData* UserData::_instance = nullptr;

void UserData::config(const QString &name, const QString &path){
    UserData::instance()->config_(name,path);
}
PaFile& UserData::get(const QString &name){
    return UserData::instance()->get_(name);
}
PaFile& UserData::system(){
    XX_ONCE([&]{
        UserData::instance()->config_(kSystem,XXqtDefine::getSystemDirPath()+"/userData.json");
    });
    return UserData::instance()->get_(kSystem);
}
PaFile& UserData::app(){
    XX_ONCE([&]{
        UserData::instance()->config_(kApp,XXqtDefine::getAppDirPath()+"/userData.json");
    });
    return UserData::instance()->get_(kApp);
}

UserData *UserData::instance(){
    static std::once_flag once;
    std::call_once(once ,[&](void){
        _instance = new UserData;
    });
    return _instance;
}
UserData::UserData(QObject *parent)
    : QObject(parent){
}

void UserData::config_(const QString &name, const QString &path){
    if(_nameToFile.contains(name)){
        return;
    }
    _nameToFile[name] = QSharedPointer<PaFile>(new PaFile(path));
}
PaFile& UserData::get_(const QString &name){
    Q_ASSERT(_nameToFile.contains(name));
    return *_nameToFile[name];
}
